/*
 * @Author: shiguo
 * @Date: 2022-04-27 18:17:54
 * @LastEditors: shiguo
 * @LastEditTime: 2023-03-23 15:07:44
 * @FilePath: /@aks-dev/easyui/utils/lazy.ts
 */
import type { SyncLoopCallBack } from './index.d'

export const sleep = (msec?: number) => {
    return new Promise(resolve => {
        setTimeout(resolve, msec || 350);
    });
}




export const randomcolor = () => {
    return `rgba(${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},${1})`
}





export const syncLoop = async (dataList: any[], callback: SyncLoopCallBack) => {
    const length = dataList.length;
    const O = Object(dataList);
    let k = 0;
    while (k < length) {
        if (k in O) {
            const kValue = O[k];
            await callback(kValue, k);
        }
        k++;
    }

    return Promise.resolve('SyncForeach loop over')
};



export const encryptMobilePhoneNumber = (text: string) => {
    if (text && text.length == 11) {
        let y1 = text.slice(0, 3);
        let y2 = text.slice(7);
        return y1 + '****' + y2
    }
    return text;
}

//判断是否为对象（仅为对象，不是数组也不是null）
export const isObject = (exp: any) => {
    return Object.prototype.toString.call(exp) == '[object Object]'
}

//判断是否为数组（仅为数组，不是对象也不是null）
export const isArray = (exp: any) => {
    return Object.prototype.toString.call(exp) == '[object Array]'
}

//判断是否为字符串
export const isString = (exp: any) => {
    return Object.prototype.toString.call(exp) == '[object String]'
}

//判断是否为数字（包括整数和实数）
export const isNumber = (exp: any) => {
    return Object.prototype.toString.call(exp) == '[object Number]'
}

//判断是否为null
export const isNull = (exp: any) => {
    return Object.prototype.toString.call(exp) == '[object Null]'
}

//判断是否为空对象
export const isNullObject = (obj: any) => {
    if (obj == null || obj == undefined)
        return true;

    if (Object.keys(obj).length > 0) {
        return false;
    }
    return true;

}

//判断是否为undefined
export const isUndefined = (exp: any) => {
    return Object.prototype.toString.call(exp) == '[object Undefined]'
}
/**判断两个对象是否相同 */
export const isObjectValueEqual = (a: any, b: any) => {
    // Object.getOwnPropertyNames()方法返回一个由指定对象的所有自身属性的属性名（包括不可枚举属性但不包括Symbol值作为名称的属性）组成的数组
    // 换句话来说 Object.getOwnPropertyNames()方法返回的是对象所有 key 组成的数组 list
    let aProps = Object.getOwnPropertyNames(a)
    let bProps = Object.getOwnPropertyNames(b)
    if (aProps.length != bProps.length) {
        return false
    }

    for (let i = 0; i < aProps.length; i++) {
        let propName = aProps[i]
        if (typeof a[propName] === 'object') {
            let judge = isObjectValueEqual(a[propName], b[propName])
            if (!judge) {
                return false
            }
        } else if (a[propName] !== b[propName]) {
            return false
        }
    }
    return true
}

export const deepEqual = (x: any, y: any) => {
    let prototype_x = Object.prototype.toString.call(x)
    let prototype_y = Object.prototype.toString.call(y)

    if (prototype_x == '[object Undefined]') {
        prototype_x = '[object Null]'
    }
    if (prototype_y == '[object Undefined]') {
        prototype_y = '[object Null]'
    }

    if (prototype_x != prototype_y) {
        return false
    }

    /**以下类型相同比较 */
    if (prototype_x == '[object Object]') {
        if (Object.keys(x).length != Object.keys(y).length) {
            return false;
        }

        for (var key in x) {
            if (!deepEqual(x[key], y[key])) {
                return false
            }
        }
    } else if (prototype_x == '[object Array]') {
        if (x.length != y.length) {
            return false
        }
        for (let index = 0; index < x.length; index++) {
            if (!deepEqual(x[index], y[index])) {
                return false
            }

        }
    }
    /**过滤对函数的深比较 */
    else if (prototype_x == '[object Function]') {
        return true
    } else {
        /**其它类型值比较 */
        return x == y
    }

    return true
}

// 定义一个深拷贝函数  接收目标target参数
export function deepClone(target: any): any {
    // 定义一个变量
    let result: any;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
        // 如果是一个数组的话
        if (Array.isArray(target)) {
            result = []; // 将result赋值为一个数组，并且执行遍历
            for (let i in target) {
                // 递归克隆数组中的每一项
                result.push(deepClone(target[i]))
            }
            // 判断如果当前的值是null的话；直接赋值为null
        } else if (target === null) {
            result = null;
            // 判断如果当前的值是一个RegExp对象的话，直接赋值
        } else if (target.constructor === RegExp) {
            result = target;
        } else {
            // 否则是普通对象，直接for in循环，递归赋值对象的所有值
            result = {};
            for (let i in target) {
                result[i] = deepClone(target[i]);
            }
        }
        // 如果不是对象的话，就是基本数据类型，那么直接赋值
    } else {
        result = target;
    }
    // 返回最终结果
    return result;
}

export const isPhoneNumber = (str: string) => {
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(str)) {
        return false;
    }
    return true;
}



/**
       *
       * @param dateStr yyyy-MM-dd HH:mm:ss
       * @returns {string}
       */
export const toDateFriendly = (dateStr: string) => {
    //af-测试可用
    if (!dateStr) {
        return ''
    }

    let dateTimeStamp = Date.parse(dateStr.replace(/-/gi, "/"));
    let minute = 1000 * 60;
    let hour = minute * 60;
    let day = hour * 24;
    let halfamonth = day * 15;
    let month = day * 30;
    let now = new Date().getTime();
    let diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
        return '';
    }
    let monthC = diffValue / month;
    let weekC = diffValue / (7 * day);
    let dayC = diffValue / day;
    let hourC = diffValue / hour;
    let minC = diffValue / minute;
    let result = '';
    if (monthC >= 1) {
        result = "" + parseInt(monthC.toString()) + "月前";
    } else if (weekC >= 1) {
        result = "" + parseInt(weekC.toString()) + "周前";
    } else if (dayC >= 1) {
        result = "" + parseInt(dayC.toString()) + "天前";
    } else if (hourC >= 1) {
        result = "" + parseInt(hourC.toString()) + "小时前";
    } else if (minC >= 1) {
        result = "" + parseInt(minC.toString()) + "分钟前";
    } else
        result = "刚刚";
    return result;
}

export const isChainChar = (str: string) => {
    var index = escape(str).indexOf("%u");
    if (index < 0)
        return false;

    return true;
}

export const isHaveChartCount = (str: string) => {
    if (/[a-z]/i.test(str)) {
        return str.match(/[a-z]/ig)?.length;
    }
    return 0;
}

export const isHaveNumberCount = (str: string) => {
    if (/[0-9]/i.test(str)) {
        return str.match(/[0-9]/ig)?.length;
    }
    return 0;
}



export const isHaveChinese = (text: string) => {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    if (reg.test(text)) {
        return true;
    } else {
        return false;
    }
}
export const isHaveEmojiCharact = (substring: string) => {
    for (var i = 0; i < substring.length; i++) {
        var hs = substring.charCodeAt(i);
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                var ls = substring.charCodeAt(i + 1);
                var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    return true;
                }
            }
            
        } else if (substring.length > 1) {
            var ls = substring.charCodeAt(i + 1);
            if (ls == 0x20e3) {
                return true;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                return true;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                return true;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                return true;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                return true;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
                || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
                || hs == 0x2b50) {
                return true;
            }
        }
    }

    return false
}



export const getUuid = () => {
    let s: any[] = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    `   ][poi]`
    var uuid = s.join("");
    return uuid
}


